
package zj.com.activities;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendPosition;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.LargeValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;


import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import zj.com.app.ZjApplication;
import zj.com.model.GsTj;
import zj.com.model.GsTjOrg;
import zj.com.util.LogUtils;
import zj.com.view.MyMarkerView;
import zj.com.zj.R;

public class BarChartActivityMultiDataset extends BaseActivity implements OnSeekBarChangeListener,
        OnChartValueSelectedListener {

    private BarChart mChart;
    private SeekBar mSeekBarX, mSeekBarY;
    private TextView tvX, tvY;
    
    private Typeface tf;
    public ImageView back_iv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_barchart);

        tvX = (TextView) findViewById(R.id.tvXMax);
        tvY = (TextView) findViewById(R.id.tvYMax);

        mSeekBarX = (SeekBar) findViewById(R.id.seekBar1);
        mSeekBarX.setOnSeekBarChangeListener(this);
        mSeekBarX.setVisibility(View.GONE);
        mSeekBarY = (SeekBar) findViewById(R.id.seekBar2);
        mSeekBarY.setOnSeekBarChangeListener(this);
        mSeekBarY.setVisibility(View.GONE);

        back_iv = (ImageView) findViewById(R.id.back_iv);
        back_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        });
        mChart = (BarChart) findViewById(R.id.chart1);
        mChart.setOnChartValueSelectedListener(this);
        mChart.setDescription("");

//        mChart.setDrawBorders(true);
        
        // scaling can now only be done on x- and y-axis separately
        mChart.setPinchZoom(false);

        mChart.setDrawBarShadow(false);


        mChart.setDrawGridBackground(false);

        // create a custom MarkerView (extend MarkerView) and specify the layout
        // to use for it
        MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view);

        // define an offset to change the original position of the marker
        // (optional)
        // mv.setOffsets(-mv.getMeasuredWidth() / 2, -mv.getMeasuredHeight());

        // set the marker to the chart
        // mChart.setMarkerView(mv);

        mSeekBarX.setProgress(10);
        mSeekBarY.setProgress(100);

        tf = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");

        Legend l = mChart.getLegend();
        l.setPosition(LegendPosition.RIGHT_OF_CHART_INSIDE);
        l.setTypeface(tf);
        l.setYOffset(0f);
        l.setYEntrySpace(0f);
        l.setTextSize(8f);

        XAxis xl = mChart.getXAxis();
        xl.setTypeface(tf);

        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setTypeface(tf);
        leftAxis.setValueFormatter(new LargeValueFormatter());
        leftAxis.setDrawGridLines(false);
        leftAxis.setSpaceTop(30f);
        leftAxis.setDrawLabels(false);
        leftAxis.setAxisMinValue(0f); // this replaces setStartAtZero(true)

        mChart.getAxisRight().setEnabled(false);

        initData();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.bar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.actionToggleValues: {
                for (IBarDataSet set : mChart.getData().getDataSets())
                    set.setDrawValues(!set.isDrawValuesEnabled());

                mChart.invalidate();
                break;
            }
            case R.id.actionTogglePinch: {
                if (mChart.isPinchZoomEnabled())
                    mChart.setPinchZoom(false);
                else
                    mChart.setPinchZoom(true);

                mChart.invalidate();
                break;
            }
            case R.id.actionToggleAutoScaleMinMax: {
                mChart.setAutoScaleMinMaxEnabled(!mChart.isAutoScaleMinMaxEnabled());
                mChart.notifyDataSetChanged();
                break;
            }
            case R.id.actionToggleBarBorders: {
                for (IBarDataSet set : mChart.getData().getDataSets())
                    ((BarDataSet)set).setBarBorderWidth(set.getBarBorderWidth() == 1.f ? 0.f : 1.f);

                mChart.invalidate();
                break;
            }
            case R.id.actionToggleHighlight: {
                if(mChart.getData() != null) {
                    mChart.getData().setHighlightEnabled(!mChart.getData().isHighlightEnabled());
                    mChart.invalidate();
                }
                break;
            }
            case R.id.actionToggleHighlightArrow: {
                if (mChart.isDrawHighlightArrowEnabled())
                    mChart.setDrawHighlightArrow(false);
                else
                    mChart.setDrawHighlightArrow(true);
                mChart.invalidate();
                break;
            }
            case R.id.actionSave: {
                // mChart.saveToGallery("title"+System.currentTimeMillis());
                mChart.saveToPath("title" + System.currentTimeMillis(), "");
                break;
            }
            case R.id.animateX: {
                mChart.animateX(3000);
                break;
            }
            case R.id.animateY: {
                mChart.animateY(3000);
                break;
            }
            case R.id.animateXY: {

                mChart.animateXY(3000, 3000);
                break;
            }
        }
        return true;
    }

    public void initData(){

        int type = getIntent().getIntExtra("type",0);
        List<GsTj> gjList = ZjApplication.gstjList;

        ArrayList<String> xVals = new ArrayList<String>();
        List<List<BarEntry>> barEntryList = new ArrayList<>();
        List<BarDataSet> barsetList = new ArrayList<>();
        Random rand = new Random();


        if(gjList == null || gjList.size() == 0) return;


        for(GsTj tj:gjList){
            xVals.add(tj.getName());

        }


        List<GsTjOrg> orgs = gjList.get(0).getOrgsList();



        Map<String,List<BarEntry>> map= new HashMap<>();
        Map<String,String> nameMap= new HashMap<>();
        for(GsTjOrg org:orgs){

           List<BarEntry> barList= new ArrayList<>();
            map.put(org.getOrgCode(), barList);
            nameMap.put(org.getOrgCode(),org.getOrgName());
        }

        for(int i=0;i<gjList.size();i++){
            GsTj tj = gjList.get(i);

            for(int j=0;j<tj.getOrgsList().size();j++){
                GsTjOrg org = tj.getOrgsList().get(j);
                List<BarEntry> barList = map.get(org.getOrgCode());
                barList.add(new BarEntry(org.getAnalysisCount(),i));

            }
        }


        List<String> names = new ArrayList<>();
        for (String key : map.keySet()) {
            barEntryList.add(map.get(key));
            names.add(nameMap.get(key));
        }


        if (mChart.getData() != null &&
                    mChart.getData().getDataSetCount() > 0) {

                for(int i=0;i<barEntryList.size();i++){
                    BarDataSet barset =  (BarDataSet)mChart.getData().getDataSetByIndex(i);
                    barset.setYVals(barEntryList.get(i));
                    mChart.getData().notifyDataChanged();
                    mChart.notifyDataSetChanged();
                }

                mChart.getData().setXVals(xVals);
                mChart.getData().notifyDataChanged();
                mChart.notifyDataSetChanged();

               LogUtils.getInstance().error("==========data=================");


            }else{

                   for(int i=0;i<barEntryList.size();i++) {
                       List<BarEntry> bars = barEntryList.get(i);
                       BarDataSet set = new BarDataSet(bars,names.get(i));
                       set.setColor(Color.rgb(rand.nextInt(200), rand.nextInt(300), rand.nextInt(200)));
                       barsetList.add(set);

                   }

                ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
                for(int i=0;i<barsetList.size();i++){
                    BarDataSet set =   barsetList.get(i);
                    dataSets.add(set);
                }

               LogUtils.getInstance().error("xVals===="+xVals.size()+"  dataSets =="+dataSets.size());
                BarData data = new BarData(xVals, dataSets);
                data.setValueFormatter(new LargeValueFormatter());
                data.setGroupSpace(80f);
                data.setValueTypeface(tf);

                mChart.setData(data);
            }

            mChart.invalidate();


    }


    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

//        tvX.setText("" + (mSeekBarX.getProgress() * 3));
//        tvY.setText("" + (mSeekBarY.getProgress()));
//
//        ArrayList<String> xVals = new ArrayList<String>();
//        for (int i = 0; i < mSeekBarX.getProgress(); i++) {
//            xVals.add((i+1990) + "");
//        }
//
//        ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();
//        ArrayList<BarEntry> yVals2 = new ArrayList<BarEntry>();
//        ArrayList<BarEntry> yVals3 = new ArrayList<BarEntry>();
//
//        float mult = mSeekBarY.getProgress() * 1000f;
//
//        for (int i = 0; i < mSeekBarX.getProgress(); i++) {
//            float val = (float) (Math.random() * mult) + 3;
//            LogUtils.getInstance().error("val=="+val+", i==="+i);
//            yVals1.add(new BarEntry(val, i));
//        }
//
//        for (int i = 0; i < mSeekBarX.getProgress(); i++) {
//            float val = (float) (Math.random() * mult) + 3;
//            yVals2.add(new BarEntry(val, i));
//        }
//
//        for (int i = 0; i < mSeekBarX.getProgress(); i++) {
//            float val = (float) (Math.random() * mult) + 3;
//            yVals3.add(new BarEntry(val, i));
//        }
//
//        BarDataSet set1, set2, set3;
//
//        if (mChart.getData() != null &&
//                mChart.getData().getDataSetCount() > 0) {
//            set1 = (BarDataSet)mChart.getData().getDataSetByIndex(0);
//            set2 = (BarDataSet)mChart.getData().getDataSetByIndex(1);
//            set3 = (BarDataSet)mChart.getData().getDataSetByIndex(2);
//            set1.setYVals(yVals1);
//            set2.setYVals(yVals2);
//            set3.setYVals(yVals3);
//            mChart.getData().setXVals(xVals);
//            mChart.getData().notifyDataChanged();
//            mChart.notifyDataSetChanged();
//        } else {
//            // create 3 datasets with different types
//            set1 = new BarDataSet(yVals1, "Company A");
//            // set1.setColors(ColorTemplate.createColors(getApplicationContext(),
//            // ColorTemplate.FRESH_COLORS));
//            set1.setColor(Color.rgb(104, 241, 175));
//            set2 = new BarDataSet(yVals2, "Company B");
//            set2.setColor(Color.rgb(164, 228, 251));
//            set3 = new BarDataSet(yVals3, "Company C");
//            set3.setColor(Color.rgb(242, 247, 158));
//
//            ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
//            dataSets.add(set1);
//            dataSets.add(set2);
//            dataSets.add(set3);
//
//            BarData data = new BarData(xVals, dataSets);
////        data.setValueFormatter(new LargeValueFormatter());
//
//            // add space between the dataset groups in percent of bar-width
//            data.setGroupSpace(80f);
//            data.setValueTypeface(tf);
//
//            mChart.setData(data);
//        }
//
//        mChart.invalidate();
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
        Log.i("Activity", "Selected: " + e.toString() + ", dataSet: " + dataSetIndex);
    }

    @Override
    public void onNothingSelected() {
        Log.i("Activity", "Nothing selected.");
    }
}
